package com.yonyou.distribute.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yonyou.distribute.mapper.StockMapper;
import com.yonyou.distribute.pojo.Stock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.locks.ReentrantLock;

/**
 * p6: 使用 jvm 本地锁解决 mysql 超卖问题
 *
 * http://localhost/mysql/cluster/stock/deduct
 */
@Slf4j
@Service
public class MysqlService_3 {

    @Resource
    private StockMapper stockMapper;

    @Value("${server.port}")
    private Integer port;

    /**
     * jvm 本地锁 解决单机超卖
     * 但是三种情况会导致 jvm 本地锁失效
     * 1、多例
     * 2、事务
     * 3、集群  *** ***  nginx
     */
    private ReentrantLock lock = new ReentrantLock();
    public void deduct(){
        lock.lock();
        try {
            Stock stock = this.stockMapper.selectOne(new QueryWrapper<Stock>().eq("product_code", "1005"));
            if(null != stock && stock.getCount() > 0){
                stock.setCount(stock.getCount() - 1);
                log.info("port:" + port);
                this.stockMapper.updateById(stock);
            }
        }finally {
            lock.unlock();
        }
    }
}
